package com.kk.xhr.model.service.impl;

import com.kk.xhr.common.pojo.BinaryEnum;
import com.kk.xhr.model.assembler.RewardStructKit;
import com.kk.xhr.model.dao.RewardDynamicSqlSupport;
import com.kk.xhr.model.dao.RewardMapper;
import com.kk.xhr.model.dto.PageDto;
import com.kk.xhr.model.dto.RewardDTO;
import com.kk.xhr.model.dto.RewardQueryRequestDTO;
import com.kk.xhr.model.entity.Reward;
import com.kk.xhr.model.service.IRewardService;
import lombok.RequiredArgsConstructor;
import org.mybatis.dynamic.sql.insert.render.MultiRowInsertStatementProvider;
import org.mybatis.dynamic.sql.render.RenderingStrategies;
import org.mybatis.dynamic.sql.where.AbstractWhereDSL;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static org.mybatis.dynamic.sql.SqlBuilder.insertMultiple;
import static org.mybatis.dynamic.sql.SqlBuilder.isEqualTo;
import static org.mybatis.dynamic.sql.SqlBuilder.isEqualToWhenPresent;
import static org.mybatis.dynamic.sql.SqlBuilder.isIn;

/**
 * 奖惩服务接口实现
 *
 * @author kkmystery
 * @version 1.0 2021/3/6
 * @since 1.0.0
 */
@Repository
@RequiredArgsConstructor
public class RewardServiceImpl implements IRewardService {
    private final RewardMapper rewardMapper;
    private final RewardStructKit instance = RewardStructKit.INSTANCE;

    /**
     * {@inheritDoc}
     */
    @Override
    public Optional<RewardDTO> queryById(Long id) {
        return rewardMapper.selectOne(dsl -> dsl
            .where(RewardDynamicSqlSupport.id, isEqualTo(id))
            .and(RewardDynamicSqlSupport.status, isEqualTo(BinaryEnum.TRUE.getValue())))
            .map(instance::toDto);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<RewardDTO> queryByUserId(Long userId) {
        return rewardMapper.select(dsl -> dsl
            .where(RewardDynamicSqlSupport.userId, isEqualTo(userId)))
            .stream()
            .map(instance::toDto)
            .collect(Collectors.toList());
    }

    @Override
    public PageDto<RewardDTO> queryPage(RewardQueryRequestDTO dto) {
        long count = rewardMapper.count(dsl -> applyQueryArgs(dsl.where(), dto));
        if (0 == count) {
            return PageDto.empty();
        }
        return new PageDto<>(count, rewardMapper.select(dsl ->
            applyQueryArgs(dsl.where(), dto)
                .orderBy(RewardDynamicSqlSupport.id.descending())
                .limit(dto.getLimit())
                .offset(dto.getOffset()))
            .stream()
            .map(instance::toDto)
            .collect(Collectors.toList()));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean add(List<Long> userIds, RewardDTO dto) {
        if (userIds.isEmpty()) {
            return false;
        }
        List<Reward> rewardList = userIds.stream()
            .distinct()
            .map(id -> instance.toEntity(dto).withUserId(id))
            .collect(Collectors.toList());
        MultiRowInsertStatementProvider<Reward> provider = insertMultiple(rewardList)
            .into(RewardDynamicSqlSupport.reward)
            .map(RewardDynamicSqlSupport.userId).toProperty("userId")
            .map(RewardDynamicSqlSupport.rewardDate).toProperty("rewardDate")
            .map(RewardDynamicSqlSupport.reason).toProperty("reason")
            .map(RewardDynamicSqlSupport.money).toProperty("money")
            .map(RewardDynamicSqlSupport.type).toProperty("type")
            .build().render(RenderingStrategies.MYBATIS3);
        return userIds.size() == rewardMapper.insertMultiple(provider);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean modify(RewardDTO dto) {
        if (null == dto.getId()) {
            return false;
        }
        return 1 == rewardMapper.updateByPrimaryKeySelective(instance.toEntity(dto));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean modifyStatus(Long id, BinaryEnum status) {
        if (null == status) {
            return false;
        }
        return 1 == rewardMapper.updateByPrimaryKeySelective(new Reward().withId(id).withStatus(status.getValue()));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean modifyStatus(List<Long> ids, BinaryEnum status) {
        if (CollectionUtils.isEmpty(ids) || null == status) {
            return false;
        }
        return ids.size() == rewardMapper.update(dsl -> dsl
            .set(RewardDynamicSqlSupport.status).equalTo(status.getValue())
            .where(RewardDynamicSqlSupport.id, isIn(ids)));
    }

    private <T extends AbstractWhereDSL<T>> T applyQueryArgs(T where, RewardQueryRequestDTO dto) {
        where.and(RewardDynamicSqlSupport.userId, isEqualToWhenPresent(dto.getUserId()));
        if (null != dto.getType()) {
            where.and(RewardDynamicSqlSupport.type, isEqualTo(dto.getType().getValue()));
        }
        if (null != dto.getStatus()) {
            where.and(RewardDynamicSqlSupport.status, isEqualTo(dto.getStatus().getValue()));
        }
        return where;
    }
}
